<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目标段" prop="institutionCode">
        <el-select
          v-model="queryParams.institutionCode"
          placeholder="请选择"
          size="small"
          style="width: 240px" @change="handleBidChange"
        >
          <el-option-group
            v-for="group in projectBidOptions"
            :key="group.name"
            :label="group.name">
            <el-option
              v-for="item in group.bids"
              :key="item.code"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['plan:profile:schedule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['plan:profile:schedule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-promotion"
          size="mini"
          :disabled="single"
          @click="handleDelivery"
          v-hasPermi="['plan:profile:schedule:delivery']"
        >传送</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-lock"
          size="mini"
          :disabled="multiple"
          @click="handleLock"
          v-hasPermi="['plan:profile:schedule:lock']"
        >锁定</el-button>
      </el-col>



      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="checkSelectable" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="标段" align="center" prop="institutionName" />
      <el-table-column label="申请名称" align="center" prop="applyName" />
      <el-table-column label="当前用户" align="center" prop="currentUserName" width="200" />
      <el-table-column label="是否锁定" align="center" prop="status" width="200">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_string_yes_no" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-grid"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-unlock"
            @click="handleUnlock(scope.row)"
            v-if="scope.row.status == '1'"
            v-hasPermi="['plan:profile:schedule:unlock']"
          >解锁</el-button>
        </template>
      </el-table-column>
      <el-table-column label="流程图" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            @click="handleWorkflow(scope.row)"
          >流程图</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改形象进度对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" style="padding-top: 150px;" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目标段" prop="institutionCode" label-width="100px">
          <el-select v-model="form.institutionCode" placeholder="请选择项目标段" style="width: 100%">
            <el-option
              v-for="item in bidOptions"
              :key="item.institutionCode"
              :label="item.institutionName"
              :value="item.institutionCode">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="日　　期" prop="date" label-width="100px">
          <el-date-picker clearable
            style="width: 100%"
            v-model="form.date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期"
          >
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 传送对话框 -->
    <el-dialog :title="delivery.title" :visible.sync="delivery.open" :close-on-click-modal="false" width="700px" style="margin-top: 150px" append-to-body>
      <el-form ref="deliveryForm" :model="deliveryForm" :rules="deliveryRules" label-width="80px">
        <el-divider content-position="left"><i class="el-icon-s-operation"></i>选择节点</el-divider>
        <el-form-item label="" prop="workflowNodeUuid" label-width="100px">
          <el-radio-group v-model="deliveryForm.workflowNodeUuid" @change="deliveryNodeChange">
            <el-radio style="width: 100px"
                      v-for="item in deliveryNodeOptions"
                      :key="item.workflowNodeUuid"
                      :label="item.workflowNodeUuid"
            >{{item.workflowNodeName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-divider content-position="left"><i class="el-icon-user-solid"></i>选择用户</el-divider>
        <el-form-item label="" prop="user" label-width="100px">
          <el-radio-group v-model="deliveryForm.user">
            <el-radio style="width: 100px"
                      v-for="item in deliveryNodeUserOptions"
                      :key="item.userName"
                      :label="item.userName"
            >{{item.nickName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-divider content-position="left"><i class="el-icon-s-order"></i>备注信息</el-divider>
        <el-input v-model="deliveryForm.reason" type="textarea"/>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deliverySubmitForm">确 定</el-button>
        <el-button @click="deliveryCancel">取 消</el-button>
      </div>
    </el-dialog>

    <workflow ref="workflow" :uuid="uuid" ></workflow>

  </div>
</template>

<script>
  import {list, add, del, getMaster, delivery, lock, unLock } from "@/api/plan/profile/schedule";
  import { selectBidBranch, selectProjectBidBranch } from "@/api/project/bid";
  import { getWorkflowNode, getWorkflowNodeUser } from "@/api/common/workflow";
  import workflow from "@/views/common/workflow/workflow";
  import { getMessageCount } from "@/api/common/message";

  export default {
    name: "PlanProfileSchedule",
    dicts: ['sys_string_yes_no'],
    components: { workflow },
    data() {
      return {
        // 标段下拉框
        projectBidOptions: [],
        // 遮罩层
        loading: false,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        list: [],
        // 弹出层标题
        title: "",
        // 状态列表
        statusOptions: [{
          value: '-1',
          label: '全部'
        },{
          value: '0',
          label: '未锁定'
        }, {
          value: '1',
          label: '已锁定'
        }],
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          institutionCode: null,
          status: '-1'
        },
        // 传送参数
        delivery: {
          title: "",
          open: false
        },
        deliveryNodeOptions: [],
        deliveryNodeUserOptions: [],
        deliveryForm: {},
        deliveryRules: {
          workflowUuid: [
            {required: true, message: "请选择需要上传/回退的节点", trigger: "blur" }
          ],
          user: [
            {required: true, message: "请选择需要上传/回退的用户", trigger: "blur" }
          ]
        },
        // 文件上传参数
        file: {
          title: "",
          open: false
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          institutionCode: [
            {required: true, message: "项目标段不能为空", trigger: "blur" }
          ],
          date: [
            {required: true, message: "日期不能为空", trigger: "blur" }
          ]
        },
        // 新增标段下拉框
        bidOptions:[],
        // uuid
        uuid: null
      };
    },
    created() {
      this.getList();
      this.initBidSelect();
    },
    methods: {
      /** 非当前用户不能进行编辑和删除操作 */
      checkSelectable(row) {
        return this.isRowEdit(row);
      },
      // 是否可以编辑
      isRowEdit(row) {
        // 获取当前用户名
        let loginName = this.$store.state.user.name;
        let userName = row.currentUser;
        if (loginName == userName && row.status != 1) {
          return true;
        } else {
          return false;
        }
      },
      /** 初始化标段下拉框 */
      initBidSelect() {
        selectProjectBidBranch().then(response => {
          this.projectBidOptions = response.data;
        });
      },
      /** 查询工程计量列表 */
      getList() {
        this.loading = true;
        list(this.queryParams).then(response => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          masterId: null,
          institutionCode: null,
          institutionName: null,
          date: null,
          projectId: null,
          projectName: null,
          companyName: null,
          applyName: null,
          currentDept: null,
          currentDeptName: null,
          currentUser: null,
          currentUserName: null,
          status: "0",
          uuid: null,
          workflowUuid: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      // 传送表单重置
      deliveryReset() {
        this.deliveryForm = {
          taskUuid: null,
          workflowUuid: null,
          user: null,
          reason: null
        };
        this.deliveryNodeOptions = [];
        this.deliveryNodeUserOptions = [];
      },
      // 标段下拉框发生变化
      handleBidChange() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.masterId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加形象进度";
        selectBidBranch().then(response => {
          this.bidOptions = response.data;
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            add(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const masterIds = row.masterId || this.ids;
        this.$modal.confirm('是否确认删除选中的数据项？').then(function() {
          return del(masterIds);
        }).then(() => {
          this.getList();
          getMessageCount().then(response => {
            this.$store.commit("SET_MESSAGE_COUNT", response.messageCount);
          });
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      /** 传送按钮操作 */
      handleDelivery(row) {
        this.deliveryReset();
        const masterId = row.masterId || this.ids[0];
        getMaster(masterId).then(response => {
          const uuid = response.data.uuid;
          this.deliveryForm.taskUuid = uuid;
          getWorkflowNode({taskUuid: uuid}).then(response => {
            this.deliveryNodeOptions = response.nodes;
            this.delivery.title = "数据传送";
            this.delivery.open = true;
          });
        });
      },
      // 传送部门发生改变事件
      deliveryNodeChange(val) {
        getWorkflowNodeUser({taskUuid: this.deliveryForm.taskUuid, workflowNodeUuid: val}).then(response => {
          this.deliveryNodeUserOptions = response.users;
          this.deliveryForm.user = null;
        });
      },
      // 传送对话框取消按钮
      deliveryCancel() {
        this.delivery.open = false;
        this.deliveryReset();
      },
      /** 提交按钮 */
      deliverySubmitForm() {
        this.$refs["deliveryForm"].validate(valid => {
          if (valid) {
            this.$loading({
              lock: true,
              text: '数据传送中',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            // 传送
            delivery(this.deliveryForm).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.delivery.open = false;
              this.getList();
              this.$loading().close();
              this.deliveryReset();
              getMessageCount().then(response => {
                this.$store.commit("SET_MESSAGE_COUNT", response.messageCount);
              });
            }).catch(() => {
              this.$loading().close();
            });
          }
        });
      },
      /** 锁定按钮操作 */
      handleLock(row) {
        const masterId = row.masterId || this.ids;
        this.$modal.confirm('确认锁定选中的数据项？').then(function() {
          return lock(masterId);
        }).then(() => {
          this.getList();
          getMessageCount().then(response => {
            this.$store.commit("SET_MESSAGE_COUNT", response.messageCount);
          });
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      /** 解锁按钮操作 */
      handleUnlock(row) {
        this.reset();
        const masterId = row.masterId || this.ids
        this.$modal.confirm('确认解锁选中的数据项？').then(function() {
          return unLock(masterId);
        }).then(() => {
          this.getList();
          getMessageCount().then(response => {
            this.$store.commit("SET_MESSAGE_COUNT", response.messageCount);
          });
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      /** 形象进度详情按钮操作 */
      handleDetail(row) {
        this.$router.push({ path: '/plan/profile/schedule/detail/' + row.masterId, query: { masterId: row.masterId, uuid: row.uuid, status: row.status} })
      },
      /** 流程图按钮操作 */
      handleWorkflow(row) {
        this.$refs.workflow.show(row.uuid);
      },
    }
  };
</script>
